import { ResourceTransformer } from '../transformers/ResourceTransformer';
import { Storage } from '../Storage';

// 依赖类型
export type DependencyType = 'component' | 'code' | 'data' | 'style';

// 依赖项
export interface Dependency {
  path: string;
  type: DependencyType;
  version?: string;
  dependencies?: string[]; // 子依赖的路径
}

// 依赖图节点
interface DependencyNode {
  dependency: Dependency;
  children: Set<string>; // 子依赖的路径
  parents: Set<string>; // 父依赖的路径
  loaded: boolean;
}

export class DependencyManager {
  private dependencyGraph = new Map<string, DependencyNode>();
  private storage: Storage;
  private transformer: ResourceTransformer;

  constructor(storage: Storage, transformer: ResourceTransformer) {
    this.storage = storage;
    this.transformer = transformer;
  }

  // 注册依赖
  async registerDependency(dependency: Dependency): Promise<void> {
    // console.log('[VFS DependencyManager] 开始注册依赖:', dependency);

    const node = this.getOrCreateNode(dependency.path);
    node.dependency = dependency;

    // 注册子依赖
    if (dependency.dependencies) {
      for (const childPath of dependency.dependencies) {
        await this.addDependencyRelation(dependency.path, childPath);
        // console.log('[VFS DependencyManager] 添加依赖关系:', {
        //   parent: dependency.path,
        //   child: childPath,
        // });
      }
    }

    // console.log('[VFS DependencyManager] 依赖注册完成:', dependency);
  }

  // 添加依赖关系
  private async addDependencyRelation(parentPath: string, childPath: string): Promise<void> {
    const parentNode = this.getOrCreateNode(parentPath);
    const childNode = this.getOrCreateNode(childPath);

    parentNode.children.add(childPath);
    childNode.parents.add(parentPath);
  }

  // 获取或创建依赖节点
  private getOrCreateNode(path: string): DependencyNode {
    let node = this.dependencyGraph.get(path);
    if (!node) {
      node = {
        dependency: { path, type: 'code' }, // 默认类型
        children: new Set(),
        parents: new Set(),
        loaded: false,
      };
      this.dependencyGraph.set(path, node);
    }
    return node;
  }

  // 获取所有依赖
  async getAllDependencies(path: string): Promise<Dependency[]> {
    const visited = new Set<string>();
    const result: Dependency[] = [];

    const traverse = async (currentPath: string) => {
      if (visited.has(currentPath)) return;
      visited.add(currentPath);

      const node = this.dependencyGraph.get(currentPath);
      if (!node) return;

      result.push(node.dependency);
      for (const childPath of node.children) {
        await traverse(childPath);
      }
    };

    await traverse(path);
    return result;
  }

  // 获取直接依赖
  async getDirectDependencies(path: string): Promise<Dependency[]> {
    const node = this.dependencyGraph.get(path);
    if (!node) return [];

    return Array.from(node.children).map((childPath) => {
      const childNode = this.dependencyGraph.get(childPath);
      return childNode!.dependency;
    });
  }

  // 按类型获取依赖
  async getDependenciesByType(path: string, type: DependencyType): Promise<Dependency[]> {
    const allDeps = await this.getAllDependencies(path);
    return allDeps.filter((dep) => dep.type === type);
  }

  // 检查循环依赖
  async checkCircularDependencies(startPath: string): Promise<string[]> {
    const visited = new Set<string>();
    const pathStack: string[] = [];
    const cycles: string[][] = [];

    const dfs = (currentPath: string) => {
      const cycleStart = pathStack.indexOf(currentPath);
      if (cycleStart !== -1) {
        cycles.push(pathStack.slice(cycleStart));
        return;
      }

      if (visited.has(currentPath)) return;
      visited.add(currentPath);
      pathStack.push(currentPath);

      const node = this.dependencyGraph.get(currentPath);
      if (node) {
        for (const childPath of node.children) {
          dfs(childPath);
        }
      }

      pathStack.pop();
    };

    dfs(startPath);
    return cycles.length > 0 ? cycles[0] : [];
  }

  // 获取加载顺序
  async getLoadingOrder(path: string): Promise<string[]> {
    const visited = new Set<string>();
    const order: string[] = [];

    const visit = async (currentPath: string) => {
      if (visited.has(currentPath)) return;

      const node = this.dependencyGraph.get(currentPath);
      if (!node) return;

      // 先处理所有子依赖
      for (const childPath of node.children) {
        await visit(childPath);
      }

      visited.add(currentPath);
      order.push(currentPath);
    };

    await visit(path);
    return order;
  }

  // 标记依赖为已加载
  async markAsLoaded(path: string): Promise<void> {
    const node = this.dependencyGraph.get(path);
    if (node) {
      node.loaded = true;
    }
  }

  // 检查依赖是否已加载
  async isLoaded(path: string): Promise<boolean> {
    const node = this.dependencyGraph.get(path);
    return node ? node.loaded : false;
  }

  // 自动分析代码依赖
  async analyzeDependencies(path: string): Promise<string[]> {
    // console.log('[VFS DependencyManager] 开始分析依赖:', path);

    const content = await this.storage.getFile(path);
    if (!content) {
      // console.log('[VFS DependencyManager] 文件不存在:', path);
      return [];
    }

    const resourceType = this.transformer.getResourceTypeByPath(path);
    const dependencies: string[] = [];

    switch (resourceType.type) {
      case 'lcDocument':
        // 分析组件依赖
        dependencies.push(...(await this.analyzeComponentDependencies(content)));
        // console.log('[VFS DependencyManager] 分析组件依赖完成:', {
        //   path,
        //   dependencies,
        // });
        break;
      case 'data':
        // 分析数据模型依赖
        dependencies.push(...(await this.analyzeDataDependencies(content)));
        // console.log('[VFS DependencyManager] 分析数据模型依赖完成:', {
        //   path,
        //   dependencies,
        // });
        break;
      default:
        // 分析代码依赖
        dependencies.push(...(await this.analyzeCodeDependencies(content)));
      // console.log('[VFS DependencyManager] 分析代码依赖完成:', {
      //   path,
      //   dependencies,
      // });
    }

    // console.log('[VFS DependencyManager] 依赖分析完成:', {
    //   path,
    //   dependencies,
    // });
    return dependencies;
  }

  // 分析组件依赖
  private async analyzeComponentDependencies(content: any): Promise<string[]> {
    const dependencies: string[] = [];

    try {
      // 如果是JSON格式的低代码组件
      if (typeof content === 'string') {
        const doc = JSON.parse(content);
        // 分析组件中使用的其他组件
        if (doc.components) {
          dependencies.push(...doc.components.map((comp: any) => `/components/${comp}.tsx`));
        }
        // 分析组件使用的数据模型
        if (doc.dataModels) {
          dependencies.push(...doc.dataModels.map((model: any) => `/models/${model}.json`));
        }
        // 分析组件使用的样式
        if (doc.styles) {
          dependencies.push(...doc.styles.map((style: any) => `/styles/${style}.css`));
        }
      }
      // 如果是TypeScript/JSX组件
      else {
        const code = content.toString();
        // 分析import语句
        const importRegex = /import\s+(?:{[^}]*}|\w+)\s+from\s+['"]([^'"]+)['"]/g;
        let match;
        while ((match = importRegex.exec(code)) !== null) {
          const importPath = match[1];
          if (importPath.startsWith('.')) {
            // 相对路径转绝对路径
            dependencies.push(this.resolveRelativePath(importPath));
          }
        }

        // 分析JSX中使用的组件（大写开头的标签）
        const jsxRegex = /<([A-Z]\w+)/g;
        while ((match = jsxRegex.exec(code)) !== null) {
          dependencies.push(`/components/${match[1]}.tsx`);
        }
      }
    } catch (error) {
      console.error('分析组件依赖失败:', error);
    }

    return dependencies;
  }

  // 分析数据依赖
  private async analyzeDataDependencies(content: any): Promise<string[]> {
    const dependencies: string[] = [];

    try {
      const model = JSON.parse(typeof content === 'string' ? content : content.toString());

      // 分析模型关联
      if (model.relations) {
        for (const relation of model.relations) {
          dependencies.push(`/models/${relation.targetModel}.json`);
        }
      }

      // 分析字段类型依赖
      if (model.fields) {
        for (const field of Object.values(model.fields)) {
          if ((field as any).type === 'model') {
            dependencies.push(`/models/${(field as any).modelName}.json`);
          }
        }
      }
    } catch (error) {
      console.error('分析数据依赖失败:', error);
    }

    return dependencies;
  }

  // 分析代码依赖
  private async analyzeCodeDependencies(content: any): Promise<string[]> {
    const dependencies: string[] = [];

    try {
      const code = content.toString();

      // 分析import语句
      const importRegex = /import\s+(?:{[^}]*}|\w+)\s+from\s+['"]([^'"]+)['"]/g;
      let match;
      while ((match = importRegex.exec(code)) !== null) {
        const importPath = match[1];
        if (importPath.startsWith('.')) {
          dependencies.push(this.resolveRelativePath(importPath));
        }
      }

      // 分析require语句
      const requireRegex = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
      while ((match = requireRegex.exec(code)) !== null) {
        const requirePath = match[1];
        if (requirePath.startsWith('.')) {
          dependencies.push(this.resolveRelativePath(requirePath));
        }
      }

      // 分析动态import
      const dynamicImportRegex = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
      while ((match = dynamicImportRegex.exec(code)) !== null) {
        const importPath = match[1];
        if (importPath.startsWith('.')) {
          dependencies.push(this.resolveRelativePath(importPath));
        }
      }
    } catch (error) {
      console.error('分析代码依赖失败:', error);
    }

    return dependencies;
  }

  // 解析相对路径
  private resolveRelativePath(relativePath: string): string {
    // TODO: 实现相对路径解析逻辑
    return relativePath;
  }
}
